<template>
  <div id="app">
    <div class="add">
      编号：<input type="text" v-model="code" /> 品牌名称：<input
        type="text"
        v-model="productName"
      />
      <br />
      产品图片地址：<input type="text" v-model="imgSrc" /> 价格：<input
        type="text"
        v-model="price"
      />
      <input type="button" value="添加" @click="add" />
    </div>
    <div class="add">
      品牌名称：<input type="text" placeholder="请输入搜索框" />
    </div>
    <div>
      <table class="tb">
        <tr>
          <th>
            <input
              type="checkbox"
              v-model="allCheck"
              @change="allCheckChange"
            />全选
          </th>
          <th>产品图片</th>
          <th>编号</th>
          <th>品牌名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in products" :key="item.id">
          <td>
            <input type="checkbox" v-model="checks" :value="item" />
          </td>
          <td>
            <img width="100" :src="item.imgSrc" alt="" />
          </td>
          <td>
            {{ item.code }}
          </td>
          <td>
            {{ item.productName }}
          </td>
          <td>
            {{ item.price }}
          </td>
          <td>
            <button @click="decrease(item)" :disabled="item.count === 1">
              -
            </button>
            {{ item.count }}
            <button @click="increase(item)">+</button>
          </td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </table>
      <div class="add" style="text-align: center" v-show="!products.length">
        没有更多数据了
      </div>
      <h2 class="add" style="text-align: right">总价格:{{ total }}</h2>
    </div>
    <!-- <h4>{{checks}}</h4> -->
  </div>
</template>
<script>
//本地永久存储的方法 核心思想：数据只要从本地获取就可以
//封装localstoreage方法
let local = {
  get(key) {
    return JSON.parse(localStorage.getItem(key));
  },
  set(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
  },
};
//初始数据
let initiaData = [
  {
    id: 1,
    code: 112,
    imgSrc:
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn09%2F266%2Fw640h426%2F20180706%2F9f65-hexfcvk3282080.jpg&refer=http%3A%2F%2Fn.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1669952276&t=c74cb7b27d41e71d820e3564601bc927",
    productName: "彭于晏",
    price: 100.11,
    count: 1,
  },
  {
    id: 2,
    code: 113,
    imgSrc: "https://b.bdstatic.com/6c204fee8e0b672ef275880206e345d4.jpeg",
    productName: "胡一天",
    price: 99,
    count: 1,
  },
  {
    id: 3,
    code: 114,
    imgSrc:
      "https://img1.baidu.com/it/u=2647875397,1421632418&fm=253&fmt=auto&app=138&f=JPEG?w=690&h=383",
    productName: "王一博",
    price: 98,
    count: 10,
  },
];
export default {
  computed: {
    total() {
      //声明一个属性，是一个函数
      let res = this.checks.reduce((total, item) => {
        //第一个是初始的变量，第二个是checks里面的每个元素
        return (total += item.price * item.count);
      }, 0); //reduce(回调函数，0)从0开始计算 数组的方法累加
      return res.toFixed(2);
    },
  },
  data() {
    return {
      allCheck: false, //全选的值
      checks: [], //选中的商品
      code: "",
      productName: "",
      imgSrc: "",
      price: "",
      products: local.get("pyy-data") ?? initiaData,
    };
  },
  watch: {
    checks(newChecks) {
      // console.log(newChecks)
      if (newChecks.length === this.products.length) {
        this.allCheck = true;
      } else {
        this.allCheck = false;
      }
    },
  },
  methods: {
    decrease(current) {
      //current当前的意思
      current.count--;
    },
    increase(current) {
      current.count++;
    },
    //全选box
    allCheckChange() {
      // console.log('allCheck')
      if (this.allCheck) {
        //所有商品都被勾选的时候
        this.checks = this.products;
      } else {
        //所有商品都被取消的时候
        this.checks = [];
      }
    },
    del(index) {
      console.log(index);
      let target = this.products.splice(index, 1); //删除
      //将products整个数据存到本地
      local.set("pyy-data", this.products);
      this.checks = this.checks.filter((item) => item.id !== target[0].id); //把相等的过滤掉 不相等的return回去
    },
    add() {
      //添加，收集输入框的数据，然后添加到products数组中，数组多一项，视图就会增加一项
      //判断（非空校验）
      if (!this.code || !this.imgSrc || !this.productName) {
        return;
      }
      //收集输入框的数据
      let obj = {
        id: Math.random().toString(32).substring(2), //获取随机数
        imgSrc: this.imgSrc,
        code: this.code,
        productName: this.productName,
        count: 1,
        price: this.prise,
      };
      //添加到数组中
      this.products.push(obj);
      //将products整个数据存到本地
      local.set("pyy-data", this.products);
    },
  },
};
</script>
<style scoped>
#app {
  width: 600px;
}
.tb {
  border-collapse: collapse;
  width: 100%;
}
.tb th {
  background-color: rgb(142, 222, 191);
  color: rgb(245, 12, 245);
}
.tb td,
.tb th {
  padding: 5px;
  border: 1px solid black;
  text-align: center;
}
.add {
  padding: 5px;
  border: 1px solid black;
  margin-bottom: 10px;
}
</style>
